package com.eclipse.organigram.views.ui;

import java.util.Map.Entry;

import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.TreeViewerColumn;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.dialogs.FilteredTree;
import org.eclipse.ui.dialogs.PatternFilter;

import com.eclipse.organigram.model.OrganigramModel;
import com.eclipse.organigram.model.entities.Category;
import com.eclipse.organigram.model.entities.Column;
import com.eclipse.organigram.model.entities.Person;

public class OrganigramComposite extends Composite {

	private TreeViewer treeViewer;

	public OrganigramComposite(Composite parent, OrganigramModel organigramModel) {
		super(parent, SWT.NONE);
		GridLayout gridLayout = new GridLayout(1, false);
		gridLayout.marginWidth = 0;
		gridLayout.marginHeight = 0;
		gridLayout.horizontalSpacing = 0;
		gridLayout.verticalSpacing = 0;
		setLayout(gridLayout);

		PatternFilter filter = createOrganigramPatternFilter();
		FilteredTree tree = new FilteredTree(this, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL, filter, true);
		tree.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
		treeViewer = tree.getViewer();
		treeViewer.setContentProvider(new OrganigramContentProvider(organigramModel));
		treeViewer.setInput(organigramModel);
		treeViewer.expandAll();
		
		treeViewer.getTree().setHeaderVisible(true);
		treeViewer.getTree().setLinesVisible(true);
		
		int columnIndex = 0;
		
		for (Column column : organigramModel.getColumns()) {
			TreeViewerColumn treeColumn = new TreeViewerColumn(treeViewer, SWT.BORDER);
			treeColumn.getColumn().setText(column.getName());
			treeColumn.getColumn().setWidth(column.getWidth());
			treeColumn.getColumn().setAlignment(SWT.RIGHT);
			treeColumn.setLabelProvider(new OrganigramColumnLabelProvider(column, columnIndex++));
		}

		treeViewer.refresh();
	}

	private PatternFilter createOrganigramPatternFilter() {
		PatternFilter filter = new PatternFilter() {
			@Override
			protected boolean isLeafMatch(Viewer viewer, Object element) {
				if (element instanceof Person) {
					Person person = (Person) element;
					for (Entry<String, String> entry : person.getPerson().entrySet()) {
						if (wordMatches(entry.getValue())) {
							return true;
						}
					}
					return false;
				} else if (element instanceof Category) {
					Category category = (Category) element;
					return wordMatches(category.getName());
				}
				return false;
			}
		};
		return filter;
	}

	public TreeViewer getViewer() {
		return treeViewer;
	}

	public void collapse() {
		treeViewer.collapseAll();
	}

	public void expand() {
		treeViewer.expandAll();
	}
}
